/**
 * Created by 功振 on 2016/2/2.
 */
angular.module('NatureCloud').controller('BuildManualCreateController', ["$scope","$state", "$uibModalInstance", "$cookies", "buildAddition", "projectListService", "utilService",
    function ($scope,$state, $uibModalInstance, $cookies, buildAddition, projectListService, utilService) {
        $scope.operation = "手动创建";
        $scope.isCodeRepoListShow = true;
        $scope.buildInfo = {};
        $scope.buildnameReg = '[a-z0-9]+(?:[._-][a-z0-9]+)*';

        $scope.ok = function () {
            if($scope.form.$valid) {

                $scope.buildInfo.user = $cookies.get("username");

                $scope.buildInfo.isCI = ($scope.buildInfo.isCI === undefined) ? false : $scope.buildInfo.isCI;

                buildAddition(angular.toJson($scope.buildInfo, true)).then(function (resp) {
                    // alert success
                    var ret = resp.data;
                    if(ret.ret == true){
                        var data = ret.data;
                        if(data.isCI === true) {
                            var urls = window.location.host;
                            var path = data.gitPath;
                            var type = '';
                            var gittype = isContains(path, "github.com");
                            if (gittype === true) {
                                type = "github";
                            }
                            var bittype = isContains(path, "bitbucket.org");
                            if (bittype === true) {
                                type = "bitbucket"
                            }
                            var _webhook = "请将该url填入到" + type + "上Webhook的URL中:" + "http://" + urls + "/opBuildInfo/webhook/" + data._id;
                            if (data.type === 'svn'){
                                alertify.alert("Sorry",'对于svn尚未开通持续集成功能',function () {

                                });
                            }else{
                                alertify.alert("请手动添加webhook URL",_webhook,function () {

                                });
                            }
                        }
                        alertify.success($scope.buildInfo.id+" build addition succeed");
                        $uibModalInstance.close(ret.data);
                    }else{
                        alertify.error($scope.buildInfo.id + " build addition failed:"+ret.error);
                        $uibModalInstance.close();
                    }


                }, function (err) {
                    // alert fail
                    alertify.error($scope.buildInfo.id + " build addition failed:"+err.data.error);
                    $uibModalInstance.close();
                });

            }
        };
        function isContains(str,substr) {
            return str.indexOf(substr) >= 0;
        }

        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };
    }
]);